'use strict';

import React, { Component } from 'react';

import {
	StyleSheet,
	Text,
	View
} from 'react-native';

function formatTime(elapsed) {
	const hour = Math.floor(elapsed / 60 / 60);
	const minute = Math.floor(elapsed / 60 - hour * 60);
	const second = elapsed % 60;
	return [hour, minute, second].map(x => x < 10 ? '0' + x : x).join(':');
}

export default class Timer extends Component < {} > {
	constructor(props) {
		super(props)
		this.state = {
			elapsed: 0,
		}
	}
	startTime = null
	lastElapsed = 0
	componentWillMount() {
		this.initTimer()
	}
	initTimer() {
		this.startTime = new Date();
		this.interval = setInterval(() => {
			//是否处于暂停
			if(this.props.paused) {
				this.lastElapsed = this.state.elapsed;
				this.startTime = new Date();
				return;
			};
			const elapsed = Math.floor((new Date() - this.startTime) / 1000) + this.lastElapsed;
			this.setState({
				elapsed,
			});
		}, 1000)
	}
	render() {
		//暂停时间的样式
		let pausedStyle = this.props.paused ? styles.pausedStyle : "";
		return(
			<View>
		      <Text style={[this.props.style,
		      				pausedStyle
		      			  ]}>
		        {formatTime(this.state.elapsed)}
		      </Text>
		    </View>
		);
	}
}

const styles = StyleSheet.create({
	container: {

	},
	pausedStyle: {
		color: "red",
	}

});